<?php
//рус
include_once(_APP_PATH. 'modules/admin/controllers/users/users_admin_http.php');
class users_admin_http_web extends users_admin_http
{
    private $_id;
    protected $_page = 1;	
	
    protected function ControllerInit()
    {   	
        $this->_id = (int)$this->Request()->get('id');

    	if ($this->Request()->hasQuery('page'))
    	{
			$this->_page = (int)$this->Request()->getQuery('page');
			if ($this->_page != $this->Request()->getCookie('page')) 
			{
				$scope = MozgRoute::Get('http')->Create(array('module' => 'admin', 'ctrl' => 'users'));
				$this->Request()->SetCookie('page', $this->_page, 0, $scope);   		
			}
    	}
    	else
    	{
    		$this->_page = (int)$this->Request()->getCookie('page');
    	}
    } 

    protected function PrimaryActionInit($basicActionName)
    {
        $this->GetModule()->GetDecorator()->SetMenuActiveElement('access/users'); 
    }     
    /**
		экшен по-умолчанию
	*/
    public function PrAction ()
    {
        $this->out_usersPr();
    }
    public function add_userPrAction ($user = null)
    {
        $this->actionTitle = 'Юзеры';

        if (!$user)
        {
	        if ($this->_id)
	        {
				$user = $this->GetMapper()->GetById($this->_id);
				if (!$user) 
				{
					$this->_id = 0;      	
				}
	        }
	        
	   		if (!$this->_id) $user = $this->GetMapper()->GetNew(); 

	   		$user->SetGrantedGroups($this->GetMapper()->GetGrantedGroups($this->_id));
        }        
        
        $t = $this->GetTemplator();
        $t->id = $this->_id;
        $t->user = $user;

        $groupsMapper = $this->GetGroupsMapper();
        $myGroupsIds = $this->User()->GetAvailableGroups();
        $myGroups = array();
        while (list(, $id) = each($myGroupsIds))
        {
     		$group = $groupsMapper->GetById($id);
			if (!$group) continue;
     		$myGroups[] = $groupsMapper->GetById($id);     	
        }
        
		$t->myGroups = $myGroups;
		$t->thumbPath = $this->GetPhotoThumbFolder('avatarsmall');
        $this->LoadTemplate ($t->render('users/_adduser.phtml'));
    }
    
    public function save_userPrAction ()
    {
        if ($this->_id)
        {
			$user = $this->GetMapper()->GetById($this->_id);
			if (!$user) 
			{
				$this->_id = 0;      	
			}
        }
        
   		if (!$this->_id) $user = $this->GetMapper()->GetNew();    	

        $user->SetUserGroup((int)$this->Request()->getPost('group_id'));
        $user->SetUserName(trim($this->Request()->getPost('username')));
        $user->SetFullName(trim($this->Request()->getPost('fullname')));
        $user->SetEmail(trim($this->Request()->getPost('email')));
        $user->SetBlocked($this->Request()->getPost('blocked') ? 1 : 0);
        
        $grantGroups = (array)$this->Request()->getPost('grant_groups');
        $mGroupId = array_search($user->GetUserGroup(), $grantGroups);
        if ($mGroupId !== false) unset($grantGroups[$mGroupId]);        
        $user->SetGrantedGroups($grantGroups);
        
        $password1 = $this->Request()->getPost('password1');
        $password2 = $this->Request()->getPost('password2');
        
        $user->SetPassword($password1);
        
        $uploadedAvatar = $this->Request()->getFile('avatar');              
        if (!$uploadedAvatar['error']) 
        {           
			$user->SetTempAvatar($uploadedAvatar['tmp_name']);   
        }         
        
		if ($password1 != $password2)
		{
			$this->Libs()->messanger->createMessage('Пароли не совпадают', MESSAGE_ERROR);	
            $this->add_userPr($user);
            return;								
		}
        else if ($this->GetMapper()->Save($user)) 
        {	  
			$this->GetMapper()->SaveGrantedGroups($user->GetUserId(), $user->GetGrantedGroups());	              	
        	
            $this->Libs()->messanger->createMessage('Данные успешно сохранены');
            MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'users'));
        } 
        else
        {
        	if ($this->GetMapper()->IsError())
        	{
        		$this->Libs()->messanger->createMessage($this->GetMapper()->GetErrorMessage(), MESSAGE_ERROR);
        	}
        	else
        	{
	            $this->Libs()->messanger->createMessage('Не удалось сохранить данные. Попробуйте снова.', MESSAGE_ERROR);     		
        	}
        	
        	$this->add_userPr($user);
            return;
        }
    }
    
    public function del_userPrAction ()
    {
        if (!$this->GetMapper()->Delete($this->_id)) 
        {
            $this->Libs()->messanger->createMessage('Юзер не найден', MESSAGE_ERROR);
        }
        else 
        {
        	$this->Libs()->messanger->createMessage('Юзер успешно удалён');
        }
        
        MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'users'));
    }
    
    public function out_usersPrAction ()
    {
        $this->actionTitle = 'Юзеры';

        $onPage = MozgCfg::GetProp('admin/users//perPage');
        
        $paginator = SysLoader::GetModule('controlls', 'http', '_web')->GetCtrl('paginator');
        $pattern = MozgRoute::Get('http')->Create(array('module' => 'admin', 'ctrl' => 'out_users', 'page' => '__page__'));
        $paginator->SetUrlPattern($pattern);        
        $pagMapper = $paginator->GetMapper();
        $pagMapper->Set(0, $this->_page, $onPage);
        
        $users = $this->GetMapper()->GetUsers($pagMapper);
        $pagMapper->SetTotalCount($this->GetMapper()->GetTotal());
        
        $t = $this->GetTemplator();
        $t->users = $users;
        $t->page = $this->_page;
        $t->pages = $paginator->Generate();
        $t->thumbPath = $this->GetPhotoThumbFolder('avatarsmall');
        $this->LoadTemplate ($t->render('users/_users.phtml'));
    }
    
    public function edit_profilePrAction ($user = null)
    {
        $this->actionTitle = 'Профиль';
        
        if ($this->User()->IsSuperUser()) return $this->view_profilePr();
        if (!$user) 
        {
			$user = $this->GetMapper()->GetById($this->User()->GetId());
			if (!$user) return $this->view_profilePr();		            
        }
        
        $t = $this->GetTemplator();
        $t->user = $user;
        $t->thumbPath = $this->GetPhotoThumbFolder('avatarsmall');
        $this->LoadTemplate ($t->render('users/_edit_profile.phtml'));
    }
    
    public function save_profilePrAction ()
    {
    	$user = $this->GetMapper()->GetById($this->User()->GetId());
    	if (!$user) return $this->view_profilePr();	

        $user->SetFullName(trim($this->Request()->getPost('fullname')));
        $user->SetEmail(trim($this->Request()->getPost('email')));
      
        $password1 = $this->Request()->getPost('password1');
        $password2 = $this->Request()->getPost('password2');
        
        $user->SetPassword($password1);
        
        $uploadedAvatar = $this->Request()->getFile('avatar');              
        if (!$uploadedAvatar['error']) 
        {           
			$user->SetTempAvatar($uploadedAvatar['tmp_name']);   
        }         
        
    	if ($password1 != $password2)
		{
			$this->Libs()->messanger->createMessage('Пароли не совпадают', MESSAGE_ERROR);	
            $this->edit_profilePr($user);
            return;								
		}        
        else if ($this->GetMapper()->Save($user)) 
        {
            $this->Libs()->messanger->createMessage('Профиль сохранён');
            MozgRoute::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'users', 'action' => 'view_profile'));
            return;
        } 
        else 
        {
        	if ($this->GetMapper()->IsError())
        	{
        		$this->Libs()->messanger->createMessage($this->GetMapper()->GetErrorMessage(), MESSAGE_ERROR);
        	}
        	else
        	{
	            $this->Libs()->messanger->createMessage('Не удалось сохранить данные. Попробуйте снова.', MESSAGE_ERROR);     		
        	}
        	
        	$this->edit_profilePr($user);
            return;
		}
    }
    
    public function view_profilePrAction ()
    {
        $this->actionTitle = 'Профиль';
        $t = $this->GetTemplator();
        $t->user = $this->User();
        $t->thumbPath = $this->GetPhotoThumbFolder('avatarsmall');
        $this->LoadTemplate ($t->render('users/_view_profile.phtml'));
    }
    
    public function get_userstatus ()
    {
    	if (!$this->User()->IsLogged())
    	{
    		return $this->GetSmallLoginForm();
    	}
    	
        $t = $this->GetTemplator();
        $t->user = $this->User();
        return $t->render('users/_userstatus.phtml');
    }
    
    public function loginPrAction ()
    {
        if ($this->User()->IsLogged()) 
        {
        	MozgRoute::Get('http')->Redirect(array('module' => 'admin'));
            return;
        } 
        
        $this->GetModule()->GetDecorator()->SetTemplate('login');
        $t = $this->GetTemplator();
        $t->user = $this->User();
        $t->postedData = $this->Request()->PostToInputs();
        $this->LoadTemplate ($t->render('users/_login.phtml'));
    }
    protected function LoadTemplate ($content)
    {
        $t = $this->GetTemplator();
        $t->title = $this->actionTitle;
        $t->content = $content;
        $this->Response()->SetBody($t->render('_main_block_template.phtml'));
    }
}